import 'package:tender_flutter/generated/json/base/json_convert_content.dart';
import 'package:tender_flutter/manager/login_manager.dart';
import 'package:tender_flutter/manager/permission_manager.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/utils/toast.dart';

import 'app_exceptions.dart';

enum Status { SUCCESS, FAIL, NOPERMISSION, LOGINEXPIRE, ERROR }

class ApiResponse<T> implements Exception {
  /// 服务端返回的状态
  Status status;

  /// 服务端返回的内容体 data
  T result;

  /// 原始数据体
  var originalData;

  /// 服务端返回的消息
  String msg;

  /// 异常信息
  AppException exception;

  /// 请求完成
  /// ignoreTip  是否忽略code做提示或其他操作
  ApiResponse.completed(response, {bool ignoreTip = false}) {
    int code = response['code'];
    this.msg = response['msg'];
    switch (code) {
      case 200:
        {
          this.originalData = response["data"];
          this.status = Status.SUCCESS;
          try {
            this.result = JsonConvert.fromJsonAsT<T>(response["data"]);
          } catch (e) {
            print("解析网络数据错误");
          }
        }
        break;
      case 905:
      case 909: // 普通会员无权限请升级VIP
      case 908: // 体验次数已用完
        {
          // 你的体验次数已用完
          this.originalData = response["data"];
          this.status = Status.NOPERMISSION;
          // 体验次数已用完
          if (!ignoreTip) {
            PermissionManager.showFreePermissDialog().then((value) {
              if (LRouter.navigator.canPop()) {
                LRouter.navigator.pop();
              }
            });
          }
        }
        break;
      case 910: // 达到当日权限接口使用上限
        {
          // 达到当日权限接口使用上限
          this.originalData = response["data"];
          this.status = Status.NOPERMISSION;
          if (!ignoreTip) {
            PermissionManager.showNumberLimitDialog().then((value) {
              if (LRouter.navigator.canPop()) {
                LRouter.navigator.pop();
              }
            });
          }
        }
        break;
      case 301: // 证书无效
      case 302: // 登录过期
      case 906: // 请登录
        {
          // 请登录
          this.originalData = response["data"];
          this.status = Status.LOGINEXPIRE;
          // 登录过期
          if (!ignoreTip) {
            LoginManager.login();
            if (LRouter.navigator.canPop()) {
              LRouter.navigator.pop();
            }
          }
        }
        break;
      default:
        {
          this.status = Status.FAIL;
          if (!ignoreTip) {
            ToastUtils.show(msg);
          }
        }
    }
  }

  /// 请求错误
  ApiResponse.error(dynamic error) {
    this.status = Status.ERROR;
    this.exception = error;
  }

  @override
  String toString() {
    return "Status : $status \n Message : $exception \n Data : $result";
  }
}
